<template>
  <div class="box">
    <div class="top_back">
      <div class="el-icon-arrow-left" @click="goback"></div>
      <div class="top_logo">
        <img src="../../../../assets/static/register/l1.png"
             alt="">
      </div>
      <div class="card">
        <!--        <div class="card_title">{{ title }}</div>-->
        <div class="card_title">
          <span>{{ $t('已经向手机') }}{{ ' ' + areaCode + ' ' + mobile }}</span>
        </div>
        <div class="card_code">
          <!--          <input/>-->
          <div v-for="(item,index) in password" :key="index">
            <input
              style="-webkit-text-security:disc;text-security:disc;"
              @keydown.delete="e=>{verifyDel(e,index)}"
              ref="input"
              @focus="inputFocus"
              @input="beInput(index)"
              type="tel"
              v-model="password[index]"/>
          </div>
        </div>
        <div class="col-wrapper" style="width: 100%">
          <span v-show="!haveSend"
                style="align-self: flex-end;margin-bottom: 20px;color: #7AC91B"
                @click="handleSendVerify">{{ $t('没有收到?重新发送') }}</span>
          <span v-show="haveSend" style="align-self: flex-end;
          margin-bottom: 20px;
          color: #7AC91B">{{ count }}s</span>
        </div>
        <div @click="save"
             class="card_btn">{{ $t('下一步') }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {login, sendVerify} from '@/api/merbership/login'
import {setToken, getToken, setReferToken} from '@/utils/tokenTools'
import {setpay_password, yz_pay_password} from '@/api/merbership/user'
import '@/styles/flax.css'
import {myInfo} from '@/api/merbership/my'

export default {
  data() {
    return {
      // ------------ 验证码 ---------------
      mobile: '',
      areaCode: '',
      count: 60,
      haveSend: false,
      verifyInterval: null,
      // ----------- 密码相关 ---------------
      title: '设置支付密码',
      password: ['', '', '', '', '', ''],
      passwordStr: '',
      repetPasswordStr: '',
      originalPassword: '',
      current: '1', // 当前状态 1-设置支付密码 2-设置重复密码
      deleteStatus: false
    }
  },
  activated() {
    this.originalPassword = this.$route.query.originalPassword
    this.password = ['', '', '', '', '', '']
    this.passwordStr = ''
    this.repetPasswordStr = ''
    this.myInfo()
  },
  watch: {
    /**
     * 定时计数
     * @param val
     */
    count(val) {
      if (val === 0) {
        clearInterval(this.verifyInterval)
        this.haveSend = false
        this.count = 60
      }
    }
  },
  methods: {
    /**
     * 重新发送验证码
     */
    handleSendVerify() {
      this.haveSend = true
      let that = this
      this.sendVerify()
      this.verifyInterval = setInterval(() => {
        that.count--
      }, 1000)
    },
    /**
     * 返回
     */
    goback() {
      switch (this.current) {
        case '1':
          this.$router.go(-1)
          break
        case '2':
          this.title = '设置支付密码'
          this.current = '1'
          this.password = ['', '', '', '', '', '']
          this.passwordStr = ''
          break
        default:
          break
      }
    },
    /**
     * 保存密码
     */
    save() {
      this.passwordStr = this.password.join('')
      if (this.passwordStr.length < 6) {
        this.$message.error('请输入六位验证码')
        return ''
      } else {
        this.$router.push({
          path: '/listPayPassword',
          query: {type: 'reset', mobile: this.mobile, d_code: this.areaCode, verify: this.passwordStr}
        })
      }
    },
    // --------------- 输入框 -----------------------
    /**
     * 获取焦点时
     */
    inputFocus() {
      // 解决密码框输满之后的失效问题 (没有input[6])
      if (this.passwordStr.length >= 6) {
        this.$refs.input[5].focus()
        return ''
      }
      // 控制焦点在未输入的第一个密码框内 为了不干扰delete 判断是否是delete操作
      if (!this.deleteStatus) {
        this.$refs.input[this.passwordStr.length].focus()
      }
    },
    /**
     * 删除
     * @param e
     * @param index
     */
    verifyDel(e, index) {
      // 标识当前操作为删除
      this.deleteStatus = true
      this.passwordStr = this.password.join('')
      if (index > 0) {
        if (this.password[index] === '') {
          this.$refs.input[index - 1].focus()
        }
      }
    },
    /**
     * 输入
     * @param index
     */
    beInput(index) {
      // 标识操作为非删除
      this.deleteStatus = false
      this.password[index] = this.password[index].replace(/\s/g, '')
      // 防止输入数字以外的字符
      if (isNaN(Number(this.password[index]))) {
        this.password[index] = this.password[index].replace(/[^\d]/g, '')
        return ''
      }
      // 组合密码 大于6位后停止组合
      if (this.passwordStr.length <= 6) {
        this.passwordStr = this.password.join('')
      }
      // 防止输入位数过多 index为5时 verifyStr为6位
      if (index > 5) {
        return ''
      }
      if (this.passwordStr.length >= 6) {
        this.$refs.input[5].focus()
        for (let i = 0; i < 6; i++) {
          if (isNaN(Number(this.passwordStr[i]))) {
            continue
          }
          this.password[i] = this.passwordStr[i]
        }
        return ''
      }
      if (index < this.password.length) {
        if (this.password[index].length >= 1) {
          this.$refs.input[this.passwordStr.length].focus()
          for (let i = 0; i < this.passwordStr.length; i++) {
            if (isNaN(Number(this.passwordStr[i]))) {
              continue
            }
            this.password[i] = this.passwordStr[i]
          }
        }
      }
    },
    // --------------------- axios --------------------
    /**
     * 设置支付密码
     */
    setpay_password() {
      const pd = {
        pay_password: this.passwordStr,
        pay_password2: this.repetPasswordStr,
        oldpay_password: this.originalPassword
      }
      setpay_password(this.$qs.stringify(pd))
        .then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
            this.$router.push({path: '/listMy'})
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    /**
     * 验证支付密码
     */
    yz_pay_password() {
      const pd = {
        pay_password: this.passwordStr
      }
      yz_pay_password(this.$qs.stringify(pd))
        .then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    /**
     * 登录
     */
    login() {
      const pd = {
        mobile: this.phone,
        code: this.verifyStr
      }
      login(this.$qs.stringify(pd))
        .then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
            setReferToken(res.data.data.refer_token)
            if (setToken(res.data.data.token) === getToken()) {
              let that = this
              setTimeout(() => {
                that.$router.push({path: '/listhome'})
              }, 1000)
            }
          } else if (res.data.code === 0) {
            this.$message.error(res.data.msg)
          }
        })
    },
    /**
     * 发送验证码
     */
    sendVerify() {
      const pd = {
        phone: this.mobile,
        d_code: this.areaCode
      }
      sendVerify(this.$qs.stringify(pd))
        .then(res => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    /**
     * 我的信息
     */
    myInfo() {
      const pd = {}
      myInfo(pd)
        .then(res => {
          if (res.data.code === 1) {
            this.mobile = res.data.data.mobile
            this.areaCode = res.data.data.code
            this.sendVerify()
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.box {
  height: 100vh;
  background-color: #fff;
}

.top_back {
  background-image: url(../../../../assets/static/register/b2.png);
  background-repeat: no-repeat;
  background-size: 100%;

  .el-icon-arrow-left {
    color: #FFFFFF;
    padding: 30px 15px;
  }

  .top_logo {
    text-align: center;

    img {
      width: 263px;
    }
  }

  .card {
    margin: 15px;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 0 15px #CCCCCC;
    border-radius: 10px;

    .card_title {
      font-size: 15px;
      font-weight: bold;
      text-align: center;
      margin: 30px 0 30px 0;
    }

    .card_mobile {
      color: #999999;
      font-size: 14px;
    }

    .card_code {
      display: flex;

      > div {
        width: 75px;
        padding: 15px 0 20px 0;
        background-image: url(../../../../assets/static/register/b1.png);
        background-repeat: no-repeat;
        background-size: 100% 100%;
        text-align: center;
        border: 0 solid transparent;
      }

      input {
        text-align: center;
        width: 20px;
        height: 20px;
        font-size: 15px;
        font-weight: bold;
        border: none;
        outline: none;
      }
    }

    .card_question {
      text-align: center;
      color: #61BF02;
      font-size: 11px;
      margin: 30px 0 10px 0;
    }

    .card_btn {
      background-image: url(../../../../assets/static/register/b3.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
      width: 294px;
      text-align: center;
      font-size: 14px;
      color: #FFFFFF;
      font-weight: bold;
      padding: 25px 0 35px 0;
    }
  }
}
</style>
